﻿using Dapper.Contrib.Extensions;
using IN.DataBase;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IN.Module
{
    public class TB_AuthorizeBll : BaseBLL<TB_AuthorizeEntity>
    {
        public bool Save(TB_RoleEntity roleEntity,ObservableCollection<TB_AuthorizeEntity> menulist, ObservableCollection<TB_AuthorizeEntity> buttonList)
        {
            bool res = false;
            using (IDbConnection dbConnection = DbConnection)
            {
                IDbTransaction transaction = dbConnection.BeginTransaction();
                try
                {
                    var sql = $"delete from TB_Authorize where ObjectId= '{roleEntity.RoleID}'";
                    IDbCommand dbCommand = dbConnection.CreateCommand();
                    dbCommand.Transaction = transaction;
                    dbCommand.CommandText = sql;
                    dbCommand.ExecuteNonQuery();

                    //菜单
                    foreach (TB_AuthorizeEntity menuEntity in menulist)
                    {
                        if (string.IsNullOrEmpty(menuEntity.AuthorizeId))
                        {
                            menuEntity.Create();
                            dbConnection.Insert(menuEntity, transaction);
                            res = true;
                        }
                        else
                        {
                            res = dbConnection.Update(menuEntity, transaction);

                        }
                        if (!res)
                        {
                            transaction.Rollback();
                            return res;
                        }
                    }
                    //按钮
                    foreach (TB_AuthorizeEntity buttonEntity in buttonList)
                    {
                        if (string.IsNullOrEmpty(buttonEntity.AuthorizeId))
                        {
                            buttonEntity.Create();
                            dbConnection.Insert(buttonEntity, transaction);
                            res = true;
                        }
                        else
                        {
                            res = dbConnection.Update(buttonEntity, transaction);

                        }
                        if (!res)
                        {
                            transaction.Rollback();
                            return res;
                        }
                    }

                    transaction.Commit();
                    return true;
                }
                catch (Exception)
                {
                    transaction.Rollback();
                }
            }
            return res;
        }
    }
}
